/**
 * @(#)AirService.java, 2013-2-14. Copyright 2013 RENREN, Inc. All rights
 *                      reserved. RENREN PROPRIETARY/CONFIDENTIAL. Use is
 *                      subject to license terms.
 */
package com.wennimei.service;

import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.stereotype.Service;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.wennimei.util.HttpUtil;
import com.wennimei.util.TimeUtil;

/**
 * @author shichen.feng@renren-inc.com
 */
@Service
public class AirService {

    @SuppressWarnings("unchecked")
    public String getAirState(String content) {
        String code = null;
        Pattern pattern = Pattern.compile("^[0-9a-zA-Z]{1,2}\\d{3,4}");
        Matcher matcher = pattern.matcher(content);
        while (matcher.find()) {
            code = matcher.group();
            break;
        }

        String date = TimeUtil.formatDate(TimeUtil.findDate(content));

        String url = "http://apis.juhe.cn/plan/s?name=%s&date=%s&key=a1ad2cf2c66f1d38e80ebefd5554094c";
        String json = HttpUtil.get(String.format(url, code, date));
        Gson gson = new Gson();
        Map<String, Object> map = gson.fromJson(json,
                new TypeToken<Map<String, Object>>() {}.getType());
        List<Map<String, String>> list = (List<Map<String, String>>) map
                .get("result");

        if (null == list || list.size() == 0)
            return "对不起，暂未查到此航班信息，请查看发送是否有误。例“CA1089”";
        Map<String, String> res = list.get(0);
        StringBuilder sb = new StringBuilder();
        sb.append(res.get("complany") + res.get("name") + ",")
                .append(res.get("start") + "到" + res.get("end") + "\r\n")
                .append("状态：" + res.get("status") + "\r\n")
                .append(" 计划起飞时间:" + safeNull(res.get("DepTime")) + "\r\n")
                .append("计划到达时间:" + safeNull(res.get("ArrTime")) + "\r\n")
                .append("预计起飞时间:" + safeNull(res.get("Dexpected")) + "\r\n")
                .append("预计到达时间:" + safeNull(res.get("Aexpected")) + "\r\n")
                .append("实时起飞时间:" + safeNull(res.get("Dactual")) + "\r\n")
                .append("实时到达时间:" + safeNull(res.get("Aactual")) + "\r\n")
                .append("准点率:" + safeNull(res.get("OnTimeRate")) + "\r\n")
                .append("飞行时间:" + safeNull(res.get("FlyTime")) + "分钟");
        return sb.toString();
    }

    public String safeNull(String str) {
        if (null == str || str.equals("null"))
            return "暂无";
        return str;
    }
}
